package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.TemplateFolder;
import com.mp.approvalreq.service.TemplateServicePrx;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/saveTemplateFolder")
public class SaveTemplateFolder extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(SaveTemplateFolder.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            User user = getReqUser(req);
            String reqBody = getContent(req);
            logger.info("保存模板分组:{}", reqBody);

            TemplateFolder folder = JSONObject.parseObject(reqBody, TemplateFolder.class);
            check(folder);
            folder.setCompanyId(user.getCompanyId());
            folder.setUser(user);

            TemplateServicePrx templateServicePrx = ServantUtils.getObject(TemplateServicePrx.class);
            templateServicePrx.saveTemplateFolder(folder);

            printSuccessJson(resp);
        } catch (Throwable throwable) {
            onThrowable(req, resp, throwable);
        }
    }

    private void check(TemplateFolder folder) {
        if (StringUtils.isEmpty(folder.getName())) {
            throw new RpcServerLogicalException(1, "分组名称不能为空");
        }
    }
}
